package liuyao.webutils.controller;

import liuyao.utils.IOUtils;
import liuyao.webutils.utils.Cache;
import liuyao.webutils.utils.HttpUtils;
import liuyao.webutils.utils.NcmUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import liuyao.webutils.common.BaseController;
import liuyao.webutils.resolver.FileUploadResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RequestMapping("/ncmFile")
@CrossOrigin
public class NcmFileController extends BaseController {

    static final String K_PROGRESS = "progress";
    static final String K_FILENAME = "filename";
    static final String K_CONTENT = "content";
    static final String K_FINISHED = "finished";

    @RequestMapping("toMp3")
    @ResponseBody
    public String ncmToMp3(String id, MultipartFile file) {
        InputStream is = null;
        String upFileName = file.getOriginalFilename();
        Map cache = Cache.get(id, ConcurrentHashMap::new);
        cache.put(K_PROGRESS, "上传完成, 转换中...");
        try {
            is = file.getInputStream();
            byte[] audio = NcmUtil.convertToMp3(is);
            // 保存缓存
            cache.put(K_FILENAME, upFileName.substring(0, upFileName.lastIndexOf(".")) + ".mp3");
            cache.put(K_CONTENT, audio);
            cache.put(K_PROGRESS, "转换完成, 下载中...");
            return jsonResponse(200, "success", id);
        } catch (Exception e) {
            cache.put(K_PROGRESS, "转换出错, " + e.getMessage());
            cache.put(K_FINISHED, true);
            return jsonResponse(500, "fail", e.getMessage());
        } finally {
            IOUtils.close(is);
        }
    }

    @GetMapping("download")
    public void ncmToMp3Download(String id, HttpServletResponse response) {
        Map cache = Cache.get(id);
        byte[] audioByte = (byte[]) cache.get(K_CONTENT);
        String mp3Name = (String) cache.get(K_FILENAME);
        cache.remove(K_CONTENT);

        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Length", "" + audioByte.length);

        ServletOutputStream sos = null;
        try {
            mp3Name = URLEncoder.encode(mp3Name, "utf-8").replace("+", " ");
            response.addHeader("Content-Disposition", "attachment;filename=" + mp3Name);
            sos = response.getOutputStream();
            sos.write(audioByte);
            sos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        IOUtils.close(sos);
        cache.put(K_PROGRESS, "下载完成.");
        cache.put(K_FINISHED, true);
    }

    @RequestMapping("toMp3Progress")
    @ResponseBody
    public String ncmToMp3Progress(String id) {
        Map resolver = Cache.get(id, ConcurrentHashMap::new);
        int code = 200;
        if ((boolean) resolver.getOrDefault(K_FINISHED, false)) {
            code = 201;
            Cache.invalidCache(id);
        }
        return jsonResponse(code, "success", resolver.getOrDefault(K_PROGRESS, "init"));
    }

}
